package com.ihai.spring.boot.sample.distributed.counter;

import com.ihai.spring.boot.sample.distributed.counter.manager.CounterManager;
import com.ihai.spring.boot.sample.distributed.counter.model.ICounter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ObjectInputStream;

/**
 * 远程接口
 *
 * @author 张驰
 * @date 2019/12/24
 */
@RestController
@RequestMapping("/counter")
public class CounterController {
    private static final Logger logger = LoggerFactory.getLogger(CounterController.class);

    @RequestMapping(value="/incr/{name}")
    public long incr(@PathVariable String name){
        ICounter counter = CounterManager.getInstance().getCounter(name);
        if(counter == null){
            CounterManager.getInstance().addCounter(name,10000);
            counter = CounterManager.getInstance().getCounter(name);
        }
        return counter.incr();
    }

    @RequestMapping(value="/add/{name}/{delta}")
    public long add(@PathVariable String name,@PathVariable int delta){
        return CounterManager.getInstance().getCounter(name).add(delta);
    }

    @RequestMapping(value="/reset/{name}")
    public void reset(@PathVariable String name){
        CounterManager.getInstance().getCounter(name).reset();
    }

    @RequestMapping(value="/{name}/{opt}")
    public long operation(@PathVariable String name,@PathVariable String opt, HttpServletRequest request){
        ICounter counter = CounterManager.getInstance().getCounter(name);
        long result = counter.get();
        try {
            ObjectInputStream objectInputStream = null;
            Object[] args = null;
            switch (opt) {
                case "setValue":
                    objectInputStream = new ObjectInputStream(request.getInputStream());
                    args = (Object[]) objectInputStream.readObject();
                    counter.setValue(Long.parseLong(args[0].toString()));
                    break;
                case "reset":
                    counter.reset();
                    result = 0;
                    break;
                case "incr":
                    result = counter.incr();
                    break;
                case "add":
                    objectInputStream = new ObjectInputStream(request.getInputStream());
                    args = (Object[]) objectInputStream.readObject();
                    result = counter.add(Integer.parseInt(args[0].toString()));
                    break;
                default:
            }
        }catch (Exception e){
            logger.error("called by remote failed.", e);
        }
        return result;
    }
}
